// subcontract/Home/productDetails/index.js
let tempsku = []//选择的规格
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    aliyunServrBaseURL: getApp().config.aliyunServrBaseURL,//阿里云公共地址
    s: app.system.statusBarHeight, //状态栏高度
    n: (app.menu.top - app.system.statusBarHeight) * 2 + app.menu.height, //导航栏高度
    h: app.menu.height, //胶囊高度
    isflag: false,
    sharePopup: null,//分享模态框实例
    DeliveryShow: false,//地址弹框
    serveShow: false,//服务
    SpecificationsShow: false,//规格
    goodsInfo: {},//商品详情信息
    goodsID: '',//商品id
    swiperCurrent: 1,//当前轮播的位置
    defaultress: {},//默认地址
    ressList: [],//我的收货地址
    info: {},//事项说明
    issMall: true,//大图小图
    tempsku: [],//临时的选中
    selectedGoods: {},//选中的商品
    navBoxTop: '',//商品距离
    ProductDetailsTop: '',//详情
    recommendTop: '',//推荐
    titleActive: 0,//选中的title
    goodsNum: 1,//购买数量
    isFlag: 1,//加入购物车还是下单
    Price: '',//商品金额
    page: 1,//页码
    pagingState: false,//分页状态
    goodsList: [],//商品
    CJinfo: {},//集采信息
    timestampToDate: getApp().timestampToDate,
    remark: '',//备注
    settlementInfo: {},
    overlayShow: false,
    current: Date.now(),
    timeData:{},//倒计时时间
  },
  onClick() {
    this.setData({ overlayShow: !this.data.overlayShow })
  },
  /**推荐商品列表 */
  async getGoodsList() {
    let object = {
      page_no: this.data.page,
      goods_tui_id: this.data.goodsID
    }
    if (!this.data.pagingState) {
      const { code, data } = await getApp().api.getGoodsList(object)
      if (code == 1) {
        this.setData({
          goodsList: this.data.goodsList.concat(data.lists)
        })
        if (data.more != 1) {
          this.setData({
            pagingState: true
          })
          return
        }
        this.setData({
          page: (this.data.page * 1) + 1
        })
        console.log(this.data.page);
      }
    }
  },
  onChenginput(event) {
    this.setData({
      remark: event.detail.value
    })
  },
  /**计算运费 */
  async settlement() {
    let { selectedGoods, goodsNum, goodsID, goodsInfo, CJinfo, defaultress } = this.data
    let object = {
      goods: JSON.stringify([{
        item_id: selectedGoods.id,
        num: goodsNum,
        goods_id: goodsID,
        shop_id: goodsInfo.shop.id,
      }]),
      address_id: defaultress.id || 0,
      jcai_id: CJinfo.jcai_id
    }
    const { code, data } = await getApp().api.settlement(object)
    if (code == 1) {
      this.setData({
        settlementInfo: data
      })
    }
  },
  /**提价下单 */
  async Jcaizc() {
    let { selectedGoods, goodsID, goodsNum, goodsInfo, defaultress, Price, remark } = this.data
    if (!defaultress.id) return getApp().showToast('请添加收货地址')
    let object = {
      item_id: selectedGoods.id,//规格id
      goods_id: goodsID,//商品id
      count: goodsNum,//数量
      goods_name: goodsInfo.name,//商品名称
      goods_price: selectedGoods.price,//规格加个
      spec_value_ids: selectedGoods.spec_value_ids,//ids
      spec_value: selectedGoods.spec_value_str,//规格
      image: selectedGoods.image,//图片
      shop_id: goodsInfo.shop.id,//店铺id
      address_id: defaultress.id,//默认地址
      total_amount: Price,//总价
      delivery_type: 1,//0 快递 1虚拟发货 2自提
      pay_way: 1,//支付方式
      // shipping_price:
      remark: remark
    }
    console.log(object);
    const { code, data } = await getApp().api.Jcaizc(object)
    if (code == 1) {
      this.unifiedpay(data.type, data.trade_id, data.order_id)
    }
  },
  /**支付方式 */
  async unifiedpay(from, trade_id, order_id) {
    let object = {
      order_id: trade_id,
      from,
      pay_way: 1
    }
    const { code, data } = await getApp().api.unifiedpay(object)
    if (code == 1) {
      const ret = await getApp().requestPay(data)
      if (ret.errMsg == 'requestPayment:ok') {
        getApp().showToast('支付成功!')
        setTimeout(() => {
          wx.navigateTo({
            url: '/subcontract/Mine/order/index',
          })
        }, 2000)
      } else {
        getApp().showToast('支付失败！')
      }
    }
  },
  /**计算金额 */
  totalPrice: function () {
    if (!this.data.selectedGoods) return getApp().showToast('请选择规格')
    let Price = (this.data.selectedGoods.price * 1) * (this.data.goodsNum * 1);
    console.log(Price);
    this.setData({
      Price
    })
  },
  onChangTime(e) {
    console.log(e.detail);
    this.setData({
      timeData: e.detail,
    });
  },
  /**数量加减 */
  onChange(e) {
    this.setData({
      goodsNum: e.detail
    })
    this.totalPrice()
    this.settlement()
  },
  /**加入购物车 */
  async addCart() {
    if (!this.data.selectedGoods.price) return getApp().showToast('请选择规格')
    let object = {
      item_id: this.data.selectedGoods.id,
      goods_num: this.data.goodsNum
    }
    const { code, data } = await getApp().api.addCart(object)
    if (code == 1) {
      getApp().showToast('添加成功!')
      this.setData({
        SpecificationsShow: false
      })
    }
  },
  /**商品收藏 */
  async changeStatus() {
    let object = {
      goods_id: this.data.goodsInfo.id
    }
    const { code, data } = await getApp().api.changeStatus(object)
    if (code == 1) {

      this.data.goodsInfo.is_collect = this.data.goodsInfo.is_collect == 0 ? '1' : 0
      this.setData({
        goodsInfo: this.data.goodsInfo
      })
    }
  },
  /**滚动 */
  scrollToElement: function (event) {
    let scrollTop = event.currentTarget.dataset.top
    console.log(scrollTop);
    wx.pageScrollTo({
      scrollTop, // 滚动到的目标位置，单位 px
      duration: 300, // 动画持续时间，单位 ms
    });
  },
  /**切换大小 */
  switchMall() {
    console.log(1);
    this.setData({
      issMall: !this.data.issMall
    })
  },
  /**选择规格 */
  selectSpecifications(event) {
    const { index, x } = event.currentTarget.dataset;
    const specValue = this.data.goodsInfo.goods_spec[index].spec_value;
    specValue.forEach((item, y) => {
      item.ischeck = y === x;
    });
    const tempsku = [...this.data.tempsku];
    tempsku[index] = specValue[x].value;
    this.setData({
      tempsku,
      goodsInfo: { ...this.data.goodsInfo }
    });
    this.recombination();
  },
  /**图片预览 */
  previewMedia(event) {
    let { index, type } = event.currentTarget.dataset
    console.log(index);
    let { goodsInfo } = this.data
    goodsInfo.goods_image.map(item => {
      item.type = 'image'
      item.url = item.uri
      return
    })
    let sources = []
    let current = 0
    if (goodsInfo.video) {
      sources = [{
        url: goodsInfo.video,
        type: 'video'
      },
      ...goodsInfo.goods_image]
      current = type == 'video' ? 0 : type == 'image' ? (index * 1) + 1 : index
    } else {
      sources = [...goodsInfo.goods_image]
      current = index
    }
    var url = sources[current].url
    wx.previewMedia({
      sources: sources, // 需要预览的资源列表
      current: current, // 当前显示的资源序号
      url: url // 当前预览资源的url链接
    })
  },
    /**规格预览 */
    previewImage(event){
      let { index,x } = event.currentTarget.dataset
      let {goodsInfo} = this.data
      console.log(index,x,goodsInfo);
       let image = goodsInfo.goods_spec[index].spec_value.map(item=>item.image)
       console.log(image);
       wx.previewImage({
        current: image[x], // 当前显示图片的http链接
        urls: image // 需要预览的图片http链接列表
      })
    },
  /**重组选择的规格 */
  async recombination() {
    let selectedGoods = this.data.goodsInfo.goods_item.find(item => item.spec_value_str === this.data.tempsku.join(','))
    this.setData({
      selectedGoods,
    })
    this.totalPrice()
    this.settlement()
  },
  /**切换地址 */
  switchress(event) {
    console.log(event);
    let item = event.currentTarget.dataset.item
    this.setData({
      defaultress: item
    })
    this.settlement()
  },
  /**轮播图切换到第几个 */
  swiperChange(event) {
    this.setData({
      swiperCurrent: event.detail.current + 1
    })
  },
  /**获取收货地址列表 */
  async addresslists() {
    const { code, data } = await getApp().api.addresslists()
    if (code == 1) {
      this.setData({
        ressList: data
      })

    }
  },

  /**获取用户默认地址 */
  async getDefault() {
    const { code, data } = await getApp().api.getDefault()
    if (code == 1) {
      this.setData({
        defaultress: data
      })
    }

  },
  /**获取商家详情 */
  async getJcaiDetail(goods_id) {
    console.log(goods_id);
    let object = {
      goods_id
    }
    const { code, data } = await getApp().api.getJcaiDetail(object)
    if (code == 1) {
      const tempsku = [...this.data.tempsku];
      for (let index = 0; index < data.goods_info.goods_spec.length; index++) {
        const element = data.goods_info.goods_spec[index];
        element.spec_value[0].ischeck = true
        tempsku[index] = element.spec_value[0].value;
      }
      let object = {
        rich: data.goods_info.content.replace(/\<img/gi, '<img style="max-width:100%;height:auto" '),
        ...data.goods_info
      }
      console.log(object);
      data.activity_end_time = getApp().timestampToDate(data.activity_end_time * 1000, 'Y年m月d日')
      this.setData({
        tempsku,
        CJinfo: data,
        goodsInfo: object
      })
      this.recombination()
    }
  },
  /**提交预约 */
  async addJcaiJoin(event) {
    let object = {
      user_id: getApp().userinfo.id,
      jcai_id:this.data.CJinfo.id
    }
    const { code, msg } = await getApp().api.addJcaiJoin(object)
    if (code == 1) {
      getApp().showToast(msg)
      this.data.CJinfo.yu_status = 1
      this.setData({
        CJinfo:this.data.CJinfo,
      })
    }
  },
  /** 跳转 */
  navigateTo(event) {
    let url = event.currentTarget.dataset.url
    console.log(url);
    wx.navigateTo({
      url,
    })
  },
  navigateBack() {
    wx.navigateBack()
  },
  openPopup(event) {
    let { type, flag } = event.currentTarget.dataset //1=分享 2=配送地址 3= 服务 4= 规格 5= 评论
    console.log(type);
    if (type == 4) {
      this.setData({
        isFlag: flag
      })
    }
    if (type == 1) {
      this.setData({ overlayShow: !this.data.overlayShow })
    } else {
      this.setData(type == 2 ? { DeliveryShow: !this.data.DeliveryShow } : type == 3 ? { serveShow: !this.data.serveShow } : type == 4 ? { SpecificationsShow: !this.data.SpecificationsShow } : type == 5 ? { commentShow: !this.data.commentShow } : '')
    }
  },
  onClose(event) {
    let type = event.currentTarget.dataset.type //1=配送地址 2=服务 3=规格 4 =评价 5=立即下单
    // console.log(type);
    this.setData(type == 1 ? { DeliveryShow: !this.data.DeliveryShow } : type == 2 ? { serveShow: !this.data.serveShow } : type == 3 ? { SpecificationsShow: !this.data.SpecificationsShow } : type == 4 ? { commentShow: !this.data.commentShow } : type == 5 ? { SpecificationsShow: !this.data.SpecificationsShow } : '')
  },
  /**事项说明 */
  async Helpdetail() {
    const { code, data } = await getApp().api.Helpdetail({ id: 6 })
    if (code == 1) {
      let object = {
        rich: data.content.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
      }
      this.setData({
        info: object
      })
    }
  },
  /**计算元素距离顶部距离 */
  calculateDistanceToTop: function () {
    let TTUL = this
    const query = wx.createSelectorQuery();
    query.select("#nav_box").boundingClientRect();
    query.select("#ProductDetails").boundingClientRect();
    query.select("#recommend").boundingClientRect();
    query.exec((res) => {
      console.log(res);
      console.log("评价元素距离页面顶部的距离", res[0]);
      console.log("详情元素距离页面顶部的距离", res[1]);
      console.log("详情元素距离页面顶部的距离", res[2]);
      TTUL.setData({
        navBoxTop: res[0].top,
        ProductDetailsTop: res[1].top - 88,
        recommendTop: res[2].top - 88
      })
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.addresslists()
    this.Helpdetail()
    const sharePopup = this.selectComponent('#share-popup');
    if (sharePopup) {
      this.setData({
        sharePopup: sharePopup
      })
    }
    this.setData({
      goodsID: options.id
    })
    this.getJcaiDetail(options.id)
    this.getGoodsList()
    setTimeout(() => {
      this.calculateDistanceToTop();
    }, 3000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getDefault()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getGoodsList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onShareTimeline(res) { },

  onPageScroll(event) {
    if (event.scrollTop < this.data.navBoxTop) {
      this.setData({
        titleActive: 0
      })
    } else if (event.scrollTop > this.data.navBoxTop && event.scrollTop < this.data.recommendTop) {
      this.setData({
        titleActive: 1
      })
    } else {
      this.setData({
        titleActive: 2
      })
    }
    this.setData({
      isflag: event.scrollTop >= 400 ? true : false
    })
  },
})